﻿Imports System.Xml.Linq
Imports Microsoft.Phone.Tasks
Imports Microsoft.Phone.Net.NetworkInformation
Imports System.Threading

Partial Public Class RSSList
    Inherits UserControl

    Public Sub New(RSSSource As String, RSSName As String)
        _RSSName = RSSName
        _RSSSource = RSSSource
        InitializeComponent()
    End Sub

    Private _RSSName As String
    Public Property RSSName() As String
        Get
            Return _RSSName
        End Get
        Set(ByVal value As String)
            _RSSName = value
        End Set
    End Property

    Private _RSSSource As String
    Public Property RSSSource() As String
        Get
            Return _RSSSource
        End Get
        Set(ByVal value As String)
            _RSSSource = value
        End Set
    End Property

    Public Sub DownloadRSS()
        Progress.Visibility = Windows.Visibility.Visible
        ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf DoDownload))
    End Sub

    Sub DoDownload()
        Dim Cache = PhoneHelpers.IsolatedStorage.LoadFromIsolatedStorage(Of List(Of RSSItem))(RSSName)
        Dispatcher.BeginInvoke(Sub()
                                   RSSListBox.ItemsSource = Cache
                                   Progress.Visibility = Windows.Visibility.Collapsed
                                   RaiseEvent DoDownloadComplete()
                               End Sub)
    End Sub

    Public Event DoDownloadComplete()

    Sub ShowList(FullList As List(Of RSSItem))
        RSSListBox.ItemsSource = FullList
    End Sub

    Private Sub RSSListBox_SelectionChanged(sender As Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles RSSListBox.SelectionChanged
        If RSSListBox.SelectedIndex <> -1 Then
            Dim Selected As RSSItem = RSSListBox.SelectedItem
            If Selected.Link <> "" Then
                Dim Web As New WebBrowserTask
                Web.Uri = New Uri(Selected.Link, UriKind.Absolute)
                Web.Show()
            End If
        End If
    End Sub
End Class